package sopraim.presenter.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ConnectionFilter implements Filter {
    public static final String USER_SESSION_FIELD = "USER_SESSION_FIELD";
    public static final String CONNECTION_ACCESS  = "/";
    
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }
    
    @Override
    public void destroy() {
    }
    
    @Override
    public void doFilter(ServletRequest servletRequest,
            ServletResponse servletResponse,
            FilterChain filterChain) throws IOException, ServletException {
        /* Cast servlet objects */
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        
        String chemin = request.getRequestURI().substring( request.getContextPath().length() );
        
        if ( chemin.startsWith( "/inc" ) ) {
            filterChain.doFilter( request, response );
            return;
        }
        
        /* Get session */
        HttpSession session = request.getSession();
        
        /* Check user identity */
        if(session.getAttribute(USER_SESSION_FIELD) == null) {
            //Tester si l'url est la racine
            //if(chemin.startsWith("UserService"))
            // response.sendRedirect("UserService?wdsl");
            //response.sendRedirect(request.getContextPath()+ChatServlet.CHAT_URL);
            if(!chemin.equals("/") && !chemin.equals("")){
                response.sendRedirect(request.getContextPath()+CONNECTION_ACCESS);
            }
            
            else {
                System.err.print(chemin);
                
                filterChain.doFilter(servletRequest, servletResponse);
            }
            
        } else {
            if(chemin.equals("/") || chemin.equals(""))
                response.sendRedirect(request.getContextPath()+"/home");
            else
                filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}
